package com.dx.gulimall.product.exception;

import com.dx.common.exception.BizCodeEnume;
import com.dx.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @author ：大雄
 * @date ：2021/11/24 23:14
 * @description： 集中处理所有异常类
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.dx.gulimall.product.controller")
public class GulimallExceprionControllerAdvice {

    //能精确匹配的异常
    @ExceptionHandler(value= MethodArgumentNotValidException.class)
    public R handleVaildException(MethodArgumentNotValidException e){
        log.error("数据校验出现问题{}，异常类型：{}",e.getMessage(),e.getClass());
        BindingResult bindingResult = e.getBindingResult();
        Map<String,String> errorMap=new HashMap<>();
        bindingResult.getFieldErrors().forEach((fieldError -> {
            errorMap.put(fieldError.getField(), fieldError.getDefaultMessage());
        }));
        return R.error(BizCodeEnume.VAILD_EXCEPTION.getCode(),BizCodeEnume.VAILD_EXCEPTION.getMsg()).put("data",errorMap);
    }

    //其他任意的异常
    @ExceptionHandler(value=Throwable.class)
    public R handleException(){

        return R.error();
    }
}
